<?php
// +----------------------------------------------------------------------
// | Description: 用户
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use think\Db;
use app\admin\model\Common;
use com\verify\HonrayVerify;
class appview extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如微信模块用weixin作为数据表前缀
     */
    protected $name = 'apply';
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $autoWriteTimestamp = DATETIME;
    // protected $insert = [
    //     'status' => 1,
    // ];
  

    public function getosAttr($value)
    {
        if($value == 2) return '其它';
    }

    /**
     * [getDataList 列表]
     * @AuthorHTL 湛慧平
     * @DateTime  2017-02-10T22:19:57+0800
     * @param     [string]                   $keywords [关键字]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [t每页数量]
     * @return    [array]                             [description]
     */



  
    public function getDataList($keywords, $page, $limit,$admin_uid,$valuedate,$os = '',$status="")
    {
        $map = [];
        if($valuedate)
        {
          $valuedate = substr($valuedate,0,10);
          $valuedate = date('Y-m-d',strtotime("$valuedate +1 day"));
          $map['time'] = ['like', '%'.$valuedate.'%'];
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%'.$keywords.'%'];
        }
        if($os)
        {
            $map['os'] = $os;
        }

        /*无用筛选*/
        // if(""!=$status)
        // {
        //     $map['status'] = $status;
        // }

        //wjf优化认证
        $map['check_aid'] = ['exp', ' is null'];
        $map['status'] = 0;

        $dataCount = $this->where($map)->count('id');
        
        $list = $this
            ->where($map);
        // 若有分页
        if ($page && $limit) {
            $list =  $list->page($page, $limit);
        }
      
        $list =  $list
        // ->field('id,status,time,money,period,order_number,check_time,check2_time,appoint_time,check2_aid,check_aid,name,uid,mobile_type,os,merchandiser_time,merchandiser2_time,fk_time,hk_time,monepassdate,lendmoneydate,first_claim_date,second_claim_date,third_claim_date,fourth_claim_date,fives_claim_date')
                     ->order('status asc,auth_type desc,check_aid asc,id desc')
                     ->select();
        $list = modelo2array($list);
        foreach($list as $key=>$value)
        {            
            $list[$key]['status'] = $this->setOverdue($value['id'],$value['appoint_time'],$value['status']);  //逾期处理     
            $mapuid['uid'] = $value['uid'];


            $count = $this->where($mapuid)->where('id','<=',$value['id'])->count();   
            if($count>=2)
            {

              //修复bug,获取上一次结束时间
                $dateArr=[];
                $last = $this->where($mapuid)->where('id','<',$value['id'])->order('time desc')->find()->toArray();
                foreach ($last as $k => $v) {

                    if($k=='appoint_time'||$k=='overdue_date') continue;
                    if(true == checkDateTime($v)){
                        $dateArr[] = $v;
                    }
                }
              $last_over_time = max($dateArr);
              
              $addcount = $count-2;
              $checkinfo = $this->where($mapuid)->field('check_aid,merchandiser,status,id,monepassdate')->select();
              $check_aid = $checkinfo[$addcount]['check_aid'];
              $ids = $checkinfo[$addcount]['id'];
              $merchandiser = $checkinfo[$addcount]['merchandiser'];
              $statuss = $checkinfo[$addcount]['status'];
              $monepassdate = $checkinfo[$addcount]['monepassdate'];
              /*if($statuss ==5)
              {
                $datacheckaid = ['check_aid'=>$check_aid];
                Db::name('apply')->where('id','>',$ids)->where($mapuid)->update($datacheckaid);
              }*/
              $list[$key]['check_aid_up'] = Db::name('admin_user')->field('username')->where('id',$check_aid)->find();
              $list[$key]['happen'] = $statuss;
              $list[$key]['monepassdate_up'] = $monepassdate;
              $list[$key]['last_over_time'] = $last_over_time; //上次结束时间

            }
            $list[$key]['counts'] = $count;
            $list[$key]['admin_uid'] = $admin_uid;
        }

        $data['list'] = $list;
        $data['dataCount'] = $dataCount;
        return $data;
    }

    /**
     * [claim 修改状态]
     * @湛慧平
     * @DateTime  2017-08-12
     * @param     string                 
     * @return    [array]
     */
    public function claim($id,$admin_uid,$uid)
    {
         $map['id'] = $id;
         if($this->where($map)->value('check_aid') > 0)
         {
            echo $this->getLastSql();
            return ['code'=>'error','message'=>'已经被认领'];
          
         }

         $this->startTrans();
         try{
  
            $nowdate = date('Y-m-d',time());
            $mapseq['nowdate'] = ['like','%'.$nowdate.'%'];
            $infocount = Db::name('claim_seq')
                         ->where('auth_admin',0)
                         ->where('admin_id',$admin_uid)
                         ->where($mapseq)
                         ->count();
            $claim_date = ['uid'=>$uid,'apply_id'=>$id,'nowdate'=>$nowdate,'auth_admin'=>0,'seq'=>$infocount+1,'admin_id'=>$admin_uid];
            Db::name('claim_seq')->insert($claim_date);
            
            $first_claim_date = date('Y-m-d H:i:s',time());
            $data = array('check_aid'=>$admin_uid,'first_claim_date'=>$first_claim_date);
            $info = $this->save($data, ['id' => $id]);  //添加至apply表中
            // 提交事务
            $this->commit();
            $data = ['code'=>'success','message'=>'认领成功'];
            return $data;
         }catch (\Exception $e) {
              // 回滚事务
            $this->rollback();
            $this->error = '失败';
            return false;
       }

    }



    public function getsexAttr($value)
    {
        $type = [0=>'女',1=>'男',2=>"未知"];
        return $type[$value];
    }

    
    /**
     * [getDataById 根据主键获取详情]
     * @zhanhuiping
     * @DateTime  2017-02-10T21:16:34+0800
     * @param     string                   $id [主键]
     * @return    [array]
     */
    public function getDataById($id = '')
    {

        $data=$this->alias('a')
            ->join('qh_user_info b','a.uid = b.uid')
            ->field('a.contract_number,a.is_report,a.delay_rate,a.credit_rate,a.period,a.credit_rate*a.period*a.money as rental,a.mobile_type,b.wechat_id,b.city,b.payday,a.bank_card_number,a.name,a.phone,b.age,b.sex,b.qq,b.zhima,b.province,b.id_card_img1,
                    b.id_card_img2,b.id_card_img3,b.tb_address,b.wx_wallet,b.alipay_bill,
                    b.wyjt_img,b.wyjt_hk_img,b.open_gid,b.id_card,b.mon_income,b.company,
                    b.company_ads,a.uid,a.money,a.time,a.check_aid,a.check_time,a.check2_aid,
                    a.check2_time,a.merchandiser,a.treasurer,a.fk_time,a.hk_time,a.period,
                    a.appoint_time,a.order_number,a.contract_number,a.rate,a.overdue_rate,a.service_rate,
                    a.procedure_rate,a.credit_rate,a.review,a.remark,b.operator_outUniqueId,a.meets,b.uid,a.upload_img,a.status,b.address,a.return_visit,b.negative_img,b.wechat_img,a.id,a.hang,a.descnote,b.zmf,is_loaning,b.job,b.directories')
            ->where('a.id',$id)
            ->find();
            $hang=substr($data['hang'], 0,11);
            if($hang=='1tolifthang')
            {
                $data['hang']=null;
            }
         $uid = $data['uid'];
         $data['showlist'] = json_decode($data['meets']);
         $list = Db::name('admin_condition')->where("(status=1 OR uid=$uid )AND step=1")->field('id,content')->select();
         $firsttrial = new Firsttrial;
         $list = $firsttrial->handlerReport($list, $uid);
         $data['list'] = $list;
         
        // 初审员
         $mapa['id'] = $data['check_aid'];
         $data['check_username'] = Db::name('admin_user')->field('username')->where($mapa)->find();
        
        //复审员
        $map1['id'] = $data['check2_aid'];
        $data['check2_username'] = Db::name('admin_user')->field('username')->where($map1)->find();
         
        //跟单员
        $map2['id'] = $data['merchandiser'];
        $data['merchandiser'] = Db::name('admin_user')->field('username')->where($map2)->find();
        
        //财务员
        $map3['id'] = $data['treasurer'];
        $data['treasurer'] = Db::name('admin_user')->field('username')->where($map3)->find();
        $map['uid'] = $data['uid'];
  
        $username = Db::name('user')->where($map)->field('username')->find();
        $data['username']=$username;
         //历史借款记录
        $historyrecord = $this->where($map)
            ->with(['predelay'])
            ->field('uid,id,fourth_claim_date,third_claim_date,time,remark,review,time,phone,status,order_number,check_aid,check_time,check2_aid
          ,check2_time,merchandiser,merchandiser2,treasurer,fk_time,hk_time,money,appoint_time,name,phone,return_visit,refuse_to_lend_money')->select();
        $historyrecord = modelo2array($historyrecord);
         foreach($historyrecord as $key=>$value)
         {
            $map1['id'] = $value['check_aid'];
            $map2['id'] = $value['check2_aid'];
            $map3['id'] = $value['merchandiser'];
            $map4['id'] = $value['treasurer'];
            $map5['id'] = $value['merchandiser2'];//催收员

            $check_aiddata = Db('admin_user')->field('username')->where($map1)->find();
            $check2_aiddata = Db('admin_user')->field('username')->where($map2)->find();
            $merchandiserdata = Db('admin_user')->field('username')->where($map3)->find();
            $treasurerdata = Db('admin_user')->field('username')->where($map4)->find();
            $merchandiser2 = Db('admin_user')->field('username')->where($map5)->find();


            $historyrecord[$key]['check_aid'] = $check_aiddata['username'];
            $historyrecord[$key]['check2_aid'] = $check2_aiddata['username'];
            $historyrecord[$key]['merchandiser'] = $merchandiserdata['username'];
            $historyrecord[$key]['treasurer'] = $treasurerdata['username'];
            $historyrecord[$key]['merchandiser2'] = $merchandiser2['username'];

             #延期+还款
             if( $historyrecord[$key]['predelay']) {
                 foreach($historyrecord[$key]['predelay'] as $k=>$v){
                     if(strpos($v['no_order'],'XQ') === false) {
                         $historyrecord[$key]['predelay'][$k]['ishk'] = 1;

                         if ($historyrecord[$key]['fourth_claim_date'] < $historyrecord[$key]['predelay'][$k]['pay_time']
                             && !is_null($historyrecord[$key]['fourth_claim_date'])
                         ) {
                             $historyrecord[$key]['predelay'][$k]['role'] = 'M1';//角色
                             $historyrecord[$key]['predelay'][$k]['roleName'] = $merchandiser2['username'];//角色姓名
                         } else {
                             $historyrecord[$key]['predelay'][$k]['role'] = 'M0';//角色
                             $historyrecord[$key]['predelay'][$k]['roleName'] = $merchandiserdata['username'];//角色姓名
                         }

                         //催收备注表
                         $whereRN['apply_id'] = $value['id'];
                         $whereRN['admin_uid'] = $GLOBALS['userInfo']['id'];
                         $whereRN['uid'] = $value['uid'];
                         $reminder = Db::name('reminder_note')->where($whereRN)->order('id desc')->find();
                         $historyrecord[$key]['predelay'][$k]['contact'] = $reminder['contact_type'];//联系方式
                         $historyrecord[$key]['predelay'][$k]['remark'] = $reminder['reminder_status'];//备注
                         $historyrecord[$key]['predelay'][$k]['contact_name'] = $reminder['contact_name'];//联系姓名方式
                     }
                 }
             }

//             if( $historyrecord[$key]['prerepay']) {
//                 foreach($historyrecord[$key]['prerepay'] as $k=>$v){
//
//                    $historyrecord[$key]['prerepay'][$k]['ishk'] = 1;
//
//                 }
//                 $historyrecord[$key]['predelay']  +=  $historyrecord[$key]['prerepay'];
//             }
         }
        // 资料补充
        
        $datainfo = Db::name('data_supplement')->where($map)->where('is_delete is null')
                                               ->field('dataname,datacontent,datatime,id,datatype,admin_id')
                                               ->select();
     
        foreach($datainfo as $key=>$value)
        {
           $where['id'] = $value['admin_id'];
           $admin_user = Db::name('admin_user')->where($where)->field('username')->find();
           $datainfo[$key]['datauser'] = $admin_user['username'];
        }

        $data['historyrecord']=$historyrecord;
        $data['datainfo']=$datainfo;

      
        return $data;
    }



    /**
     * 历史延期
     * @author cxr <1481746137@qq.com>
     * @return $this
     */
    public function predelay(){
//        $where_yanqi['qh_user_order.no_order'] = ['like', '%XQ%']; // 总
        $where_yanqi['result_pay'] = ['eq', 'SUCCESS'];
        return $this->hasMany('UserOrder','apply_id','order_number')->where($where_yanqi);
    }

    /**
     * 历史还款
     * @author cxr <1481746137@qq.com>
     * @return $this
     */
    public function prerepay(){
        $map['result_pay'] = 'SUCCESS';
        $map['no_order'] = ['notlike', '%XQ%']; //不和延期订单混淆， 失误少了个这个条件
        return $this->hasMany('UserOrder','apply_id','order_number')->where($map)->order('pay_time desc');
    }
    
    /**
     * 功能:  查询用户名
     * @Author   zhanhuiping
     * @email    18702529695@163.com
     * @DateTime 2017-09-08
     * @return   [type]              [description]
     */
    public function getusername($key,$value)
    {
        
        return $historyrecord;
    }

    /*
    * auth:zhanhuiping
    * date:2017/9/6
    * features:其它驳回恢复
    */
    public function otherdown($param)
    {
      $id = $param['param']['id'];
      $where['id'] = $id;
      $data = ['status'=>0];
      $statusdata = $this->field('status')->where($where)->find();
      if($statusdata['status']!=8)
      {
        $this->error = '状态不为其它驳回';
        return false;
      }
      $info = $this->save($data,$where);
      if(!$info)
      {
         $this->error = '解除失败';
         return false;
      }
      return ture;
    }





    /**
     * 通过id修改用户
     * @param  array   $param  [description]
     */
    public function updateDataById($param, $id)
    {
        $checkData = $this->where('id',$id)->find();

        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }
        if($param['sex']=='男'){
            $param['sex']=1;
        }elseif($param['sex']=='女'){
            $param['sex']=0;
        }
        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
        $param['update_time']=date('Y-m-d H:i:s',time());;
        $re=$this->allowField(true)->save($param,['id'=>$id]);
        $arr=array();
        $arr['username']=$param['username'];
        $arr['phone']=$param['phone'];
        $re1=Db::name('user')->where('uid',$id)->update($arr);
        if($re || $re1){
            return true;
        }else{
            $this->error = '编辑失败';
            return false;
        }
    }
    public function getName($uid)
    {
        return $this->where('uid',$uid)->value("name");
    }
    public function getPhone($uid)
    {
        return $this->where('uid',$uid)->value("phone");
    }   
    public function getCardNo($no)
    {
        return $this->where('order_number',$no)->value("bank_card_number");
    }
    public function getIdCard($uid)
    {
        return $this->where('uid',$uid)->value("id_card");
    }     
    public function resetDataById($id)
    {
        // 不能操作超级管理员
        if ($id == 1) {
            $this->error = '非法操作';
            return false;
        }
        $checkData = $this->where('uid',$id)->find();
        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }
        /*if($checkData['status']!=1){
            $this->error = '该账户已被删除或禁用！';
            return false;
        }*/
        $param=array();
        $param['password']=123456;
        $param['password'] = user_md5($param['password'],$auth_key = 'qhdkb');
        $param['last_login_time']=date('Y-m-d H:i:s',time());;
        $res=Db::name('user')->where('uid',$id)->update($param);
        if($res){
            return true;
        }else{
            $this->error = '重置失败';
            return false;
        }
    }
    /**
     * 获取所有子孙
     */
    public function getAllChild($id, &$data = [])
    {
        $map['pid'] = $id;
        $childIds = $this->where($map)->column($this->getPk());
        if (!empty($childIds)) {
            foreach ($childIds as $v) {
                $data[] = $v;
                $this->getAllChild($v, $data);
            }
        }
        return $data;
    }
    public function enableData($ids = [], $status = 1, $delSon = false)
    {
        if (empty($ids)) {
            $this->error = '修改失败';
            return false;
        }

        // 查找所有子元素
        if ($delSon && $status === '0') {
            foreach ($ids as $k => $v) {
                $childIds = $this->getAllChild($v);
                $ids = array_merge($ids, $childIds);
            }
            $ids = array_unique($ids);
        }
        $list=$this->where('id','in',$ids)->select();
        $list = modelo2array($list);
        $data['list'] = $list;
        $uids=array();
        foreach($data['list'] as &$v){
            $uids[]=$v['uid'];
        }
        try {
            Db::name('user')->where('uid','in',$uids)->setField('status', $status);
            return true;
        } catch (\Exception $e) {
            $this->error = '操作失败';
            return false;
        }
    }
    
    /**
     * [getInvitDataById 根据主键获取邀请人数详情]
     * @linchuangbin
     * @DateTime  
     * @param     string                   $id [主键]
     * @return    [array]
     */
    public function getInvitDataById($uid,$page, $limit)
    {
        $dataCount = $this->alias('a')
                    ->join('qh_invite_code b','a.uid = b.uid')
                    ->where('puid',$uid)
                    ->count('b.id');
        
        $invitName = $this->where('uid',$uid)->field('name')->find();
        $invitName = json_decode($invitName);
        $list = $this
        ->where(1);
        // 若有分页
        if ($page && $limit) {
            $list = $this->page($page, $limit);
        }
        
        $list=$this->alias('a')
        ->join('qh_invite_code b','a.uid = b.uid')
        ->field('a.name,a.qq,a.phone,a.zhima,b.create_time')
        ->where('b.puid',$uid)
        ->select();
        
        $list = modelo2array($list);
        $data['list'] = $list;
        $data['dataCount'] = $dataCount;
        $data['invitName'] = $invitName;
        return $data;
    }
    /**
     * [getData 获取单条数据]
     * @param  string $field [description]
     * @param  array  $where [description]
     * @return [type]        [description]
     */
    public function getDatas($field = '*',$where = [])
    {
      return $this->field($field)->where($where)->find();
    }

   /**
    *   
    * @param  string $field [description]
    * @param  array  $where [description]
    * @return [type]        [description]
    */
    public function getUserApplyInfo($field = '*',$where = [])
    {
        return $this->alias('a')->field($field)->join('user_info b','a.uid = b.uid',"LEFT")->where($where)->find(); 
    }
    /**
     * [getValue 根据条件获取相关字段]
     * @param  array  $where [description]
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function getValue($where = [], $value = '')
    {
      return $this->where($where)->value($value);
    }

}